import { defineStore } from "pinia";
import { isEmpty, get } from "lodash";
import { getTokenDecrypt, getUserMenuBtn, login } from "@/api/login.js";
import { clearToken, setToken } from "@/utils/token.js";
import { setFavicon } from "@/utils/domUtil.js";
import storage from "@/utils/storage.js";

export function getAreaCodeLevel(area_code) {
  return typeof area_code === "string" && area_code.split(".").length;
}

export const userInfoStore = defineStore("userInfo", {
  state: () => ({
    userMenuBtns: [],
    userData: {},
    areaCode: "",
    areaName: "",
  }),
  getters: {
    area_code: (state) => get(state, "areaCode", ""),
    area_name: (state) => get(state, "areaName", ""),
    unit_code: (state) => get(state, "userData.unitCode", ""),
    unit_name: (state) => get(state, "userData.unitName", ""),
    /* 该账号 area_code 长度 */
    area_code_level: (state) => getAreaCodeLevel(get(state, "areaCode")),
  },
  actions: {
    // 登录
    Login(params) {
      return new Promise(async (resolve, reject) => {
        const res = await login(params);
        if (res && res.code == 200) {
          const data = res.data || {};
          setToken(data.access_token);
          resolve(data);
        } else {
          reject(res);
        }
      });
    },
    // 退出
    Logout() {
      return new Promise((resolve) => {
        storage.session.removeItem("_user_info");
        storage.session.removeItem("_menu_buttons");
        this.userData = {};
        clearToken();
        resolve();
      });
    },
    // 获取用户信息
    async GetInfo() {
      if (!isEmpty(this.userData)) {
        return this.userData;
      }
      let data = storage.session.getItem("_user_info");
      if (isEmpty(data)) {
        data = await getTokenDecrypt().then((res) => (res && res.data) || {});
      }
      this.userData = data;
      this.areaCode = get(data, "areaCode", "");
      this.areaName = get(data, "area_name", "");
      storage.session.setItem("_user_info", data, { expires: 7 });
      setFavicon(data.systemIcon);
    },
    // 获取按钮权限
    async getUserMenuBtnsAsync() {
      if (!isEmpty(this.userMenuBtns)) {
        return this.userMenuBtns;
      }
      let data = storage.session.getItem("_menu_buttons");
      if (isEmpty(data)) {
        data = await getVueGlobalProperty("handleCommonResult")(
          await getUserMenuBtn()
        );
      }
      let list = data.reduce((res, key) => {
        return res.includes(key) ? res : res.concat(key);
      }, []);
      this.userMenuBtns = list;
      storage.session.setItem("_menu_buttons", list, { expires: 7 });
    },
  },
});
